import React, {useEffect, useState} from 'react';
import {Modal, Form, Skeleton} from "antd";
import ProForm, {ProFormText} from '@ant-design/pro-form';
import VditorMd from '../../../components/VditorMd'
import {showArticleServe} from "@/services/article";

const CreateOrEdit = (props) => {

  // 父类传过来的模态框显示 添加和编辑的方法 以及文章ID
  const {isModalVisible,addArticle,editId,setModelOrId} = props

  // 文本框输入的md数据
  const [vditorMdData,setVditorMdData] = useState(undefined);

  // 文本框输入的html数据
  const [vditorHtmlData,setVditorHtmlData] = useState(undefined);

  // 表单的初始值
  const [initialValues,setInitialValues] = useState();

  /**
   * 保存富文本框输入的数据
   * @param data
   */
  const inputData = (mdvalue,htmlvalue)=>{
    setVditorMdData(mdvalue)
    setVditorHtmlData(htmlvalue)
  }

  useEffect(async ()=>{
    if (editId){
      const resoule =   await showArticleServe(editId)
      setInitialValues(resoule.data)
    }
  },[])

  return (
    <div>
      <Modal
        onCancel={() => {setModelOrId(false)}}
        maskClosable={true}
        width={1200}
        title="Basic Modal"
        visible={isModalVisible}
        footer={false}
      >
        {
          initialValues == null && editId  ? <Skeleton active /> :
            <ProForm
              initialValues={initialValues}
              onFinish={
                (data) =>
                {addArticle(data,vditorMdData === undefined ? initialValues.content : vditorMdData,
                  vditorHtmlData === undefined ? initialValues.content_md : vditorHtmlData
                )}}
            >
              <input type="hidden"/>
              <ProFormText
                width="100"
                name="title"
                label="文章标题"
                rules={[
                  {
                    required: true,
                    message: '请输入文章标题',
                  },
                  {
                    min:10,
                    message: '请输入文章标题 最少10个字符',
                  },
                  {
                    max:100,
                    message: '文章标题最多100个字符',
                  },
                ]}
              />
              <ProFormText
                width="100"
                name="img"
                label="文章封面"
              />
              <Form.Item>
                <VditorMd value={initialValues ? initialValues.content_md : ''} inputData={inputData}/>
              </Form.Item>
            </ProForm>
        }

      </Modal>
    </div>
  );
};

export default CreateOrEdit;
